<script>
import Block from '../Block'
import ValueWithDateInput from '../ValueWithInput/WithDate.vue'
import ValueWithInput from '../ValueWithInput/WithInput.vue'
import ValueWithNumberInput from '../ValueWithInput/WithNumberInput.vue'
import ValueWithSelector from '../ValueWithInput/WithSelector.vue'
import Dorm from '@/components/Check/Dorm'
import PostSelector from '../Selector/postiton.vue'
import DepartmentSelector from '../Selector/department.vue'
import LeaderSelector from '../Selector/leader.vue'
import RewardPunishment from '../RewardPunishment'
import SetRoles from '../SetRoles/index.vue'

import {
  getNation,
  getMarriage,
  getSchool,
  getBank,
  getPolitic,
  getAddress,
  getPosition,
  getDept,
  getEducation
} from '@/api/basic'

import { value, atLeastN, atLeast } from '@/utils/kris_utils'
import { getAllUser } from '@/api/v2/personnel'

export default {
  components: {
    Block,
    ValueWithDateInput,
    ValueWithInput,
    ValueWithNumberInput,
    ValueWithSelector,
    RewardPunishment,

    Dorm,
    LeaderSelector,

    PostSelector,
    DepartmentSelector,
    SetRoles
  },
  props: {
    isEditing: {
      type: Boolean,
      required: true,
      default: false
    },
    profile: {
      required: true,
      default() {
        return null
      }
    },
    userID: {
      required: true,
      default: null
    }
  },
  data() {
    return {
      elementSize: 'mini',

      statusOptions: [
        { label: '在职', value: 1 },
        { label: '离职', value: 0 }
      ],

      employeeTypeOptions: [
        { label: '正式员工', value: 0 },
        { label: '实习员工', value: 1 },
        { label: '试用员工', value: 2 }
      ],

      departSalaryStatusOptions: [
        { label: '已结清', value: 1 },
        { label: '未结清', value: 0 }
      ],

      departments: [],

      switchDormDialog: {
        visible: false
      },
      referencesList: [],
      introduceList: [],
      pageArr: {
        current: 1, // 当前页
        // size: 10000, // 每页显示条数
        last_page: '',
        type:2
      }
    }
  },
  computed: {
    departmentFormatted() {
      return this.departmentFormatter(this.departments)
    },
    roomOverview() {
      const data = value(this.profile, 'apartment.data', null)
      if (data === null) { return { rows: [] } }

      if (!atLeast(data, ['name', 'rent', 'number'])) { return { rows: [] } }

      return {
        rows: [
          // {label:'地址/房间',value:`${data.dormitory.address}${data.name}`},
          { label: '可住人数', value: data.number },
          { label: '房间租金', value: data.rent }
        ]
      }
    }
  },
  created() {
    this.initData()
    this.references()
  },
  methods: {
    atLeastN,
    value,
    departmentFormatter(options = [], childrenKey = 'children') {
      const result = []

      for (const i in options) {
        const option = options[i]

        const { id, name } = option
        const tmp = { label: name, value: id }

        if (Array.isArray(option[childrenKey]) && option[childrenKey].length > 0) { tmp['children'] = this.departmentFormatter(option[childrenKey], childrenKey) }

        result.push(tmp)
      }

      return result
    },
    handleSelectedDorm(dorm) {
      this.profile.apartment = {
        label: dorm.name,
        value: dorm.id,
        data: dorm
      }
    },
    openURL(url) {
      window.location.href = url
    },
    async getDepartments() {
      const result = await getDept()
        .catch(err => {
          throw new Error('获取部门信息失败')
        })

      if (result.code !== 200 || !Array.isArray(result.data)) { throw new Error(value(result, 'message', '获取部门信息失败')) }

      this.departments = result.data
    },
    async loadData() {
      const tasks = await Promise.allSettled([
        this.getDepartments()
      ])

      const failTasks = tasks.filter(task => task.status === 'rejected')

      if (failTasks.length > 0) {
        throw new Error(failTasks[0].reason)
      }
    },
    async initData() {
      try {
        await this.loadData()
      } catch (error) {
        this.$message.error(error.message ?? '加载数据时出现异常')
      }
    },
    async references() {
      const param = {
        paginate: this.pageArr.size,
        page: this.pageArr.current
      }
      const res = await getAllUser(param)
      this.pageArr.last_page = res.meta.last_page
      this.referencesList = res.data
      for (const i in this.referencesList) {
        const option = this.referencesList[i]
        const { id, username } = option
        const tmp = { label: username, value: id }

        this.introduceList.push(tmp)
      }
    }
  }
}
</script>

<template>
  <Block title="公司档案">
    <template v-if="isEditing" #extra>
      <el-button size="mini" :loading="$attrs.isSubmitting" @click="$emit('save')">保存</el-button>
    </template>

    <div class="company-archives-container">
      <table class="company-archives">
        <tbody>
          <tr>
            <td class="label">工号</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.employeeNumber"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写工号"
              />
            </td>

            <td class="label">职位</td>
            <td class="value">
              <PostSelector
                v-model="profile.post"
                :size="elementSize"
                :is-editing="isEditing"
                init
                local-search
                placeholder="请选择职位"
                style="width: 100%;"
              />
            </td>

            <td class="label">身份</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.employeeType"
                :size="elementSize"
                placeholder="请选择身份"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="employeeTypeOptions"
              />
            </td>
          </tr>

          <tr>
            <td class="label">入职日期</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.entryDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择入职日期"
              />
            </td>

            <td class="label">部门</td>
            <td class="value">
              <DepartmentSelector
                v-model="profile.department"
                style="width: 100%;"
                :size="elementSize"
                :is-editing="isEditing"
                :options="departmentFormatted"
              />
            </td>

            <td class="label">在职状态</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.status"
                :size="elementSize"
                placeholder="请选择在职状态"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="statusOptions"
              />
            </td>
          </tr>

          <tr>
            <td class="label">实习/试用开始时间</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.practiceBeginDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择实习/试用开始时间"
              />
            </td>

            <td class="label">实习/试用结束时间</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.practiceEndDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择实习/试用结束时间"
              />
            </td>

            <td class="label">转正时间</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.dateOfbecomeARegularWorker"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择转正时间"
              />
            </td>
          </tr>

          <tr>
            <td class="label">所属领导</td>
            <td class="value">
              <LeaderSelector v-model="profile.leader" :is-editing="isEditing" />
            </td>

            <td class="label">实习/试用薪资</td>
            <td class="value">
              <ValueWithNumberInput
                v-model="profile.salaryOfPractice"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写实习/试用薪资"
              />
            </td>

            <td class="label">转正薪资</td>
            <td class="value">
              <ValueWithNumberInput
                v-model="profile.regularSalary"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写转正薪资"
              />
            </td>
          </tr>

          <tr>
            <td class="label">当前薪资</td>
            <td class="value">
              <ValueWithNumberInput
                v-model="profile.salary"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写当前薪资"
              />
            </td>

            <td class="label">劳动合同</td>
            <td class="value">
              <el-button
                v-if="profile.laborContract"
                type="text"
                @click="openURL(profile.laborContract)"
              >
                <i class="el-icon-download" />
                下载
              </el-button>
              <span v-else>-</span>

              <el-button
                v-if="isEditing"
                type="text"
                @click="$emit('uploadFile','laborContract')"
              >
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>

            <td class="label">劳动合同开始时间</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.laborContractBeginDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择劳动合同开始时间"
              />
            </td>
          </tr>

          <tr>
            <td class="label">劳动合同结束时间</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.laborContractEndDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择劳动合同结束时间"
              />
            </td>

            <td class="label">离职日期</td>
            <td class="value">
              <ValueWithDateInput
                v-model="profile.departDate"
                :is-editing="isEditing"
                :size="elementSize"
                style="width: 100%;"
                placeholder="请选择离职日期"
              />
            </td>

            <td class="label">入职方式</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.entryMethod"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写入职方式"
              />
            </td>
          </tr>

          <tr>
            <td class="label">离职原因</td>
            <td class="value">
              <ValueWithInput
                v-model="profile.reasonForLeaving"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写离职原因"
              />
            </td>

            <td class="label">入职次数</td>
            <td class="value">
              <ValueWithNumberInput
                v-model="profile.entryCount"
                :is-editing="isEditing"
                :size="elementSize"
                placeholder="请填写入职次数"
              />
            </td>

            <td class="label">所属宿舍</td>
            <td class="value">
              {{ value(profile,'apartment.label','暂无') }}
                            &nbsp;
              <el-popover
                placement="top-start"
                title="房间详情"
                width="300"
                trigger="hover"
              >
                <div>
                  <div v-for="item in roomOverview.rows" class="row">
                    <span class="label">{{ item.label }}：</span>
                    <span class="value">{{ item.value }}</span>
                  </div>
                </div>

                <el-button slot="reference" type="text">
                  <i class="el-icon-view" />
                  详情
                </el-button>
              </el-popover>
                            &nbsp;
              <el-button
                v-if="isEditing"
                type="text"
                @click="switchDormDialog.visible = true"
              >
                <i class="el-icon-edit-outline" />
                更换
              </el-button>
            </td>
          </tr>

          <tr>
            <td class="label">体检记录电子版</td>
            <td class="value">
              <el-button
                v-if="profile.physicalExamRecord"
                type="text"
                @click="openURL(profile.physicalExamRecord)"
              >
                <i class="el-icon-download" />
                下载
              </el-button>
              <span v-else>-</span>

              <el-button
                v-if="isEditing"
                type="text"
                @click="$emit('uploadFile','physicalExamRecord')"
              >
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>

            <td class="label">离职工资状态</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.departSalaryStatus"
                placeholder="请选择离职工资状态"
                style="width: 100%;"
                :is-editing="isEditing"
                :size="elementSize"
                :options="departSalaryStatusOptions"
              />
            </td>

            <td class="label">暂住证电子版</td>
            <td class="value">
              <el-button
                v-if="profile.temporaryResidencePermit"
                type="text"
                @click="openURL(profile.temporaryResidencePermit)"
              >
                <i class="el-icon-download" />
                下载
              </el-button>
              <span v-else>-</span>

              <el-button
                v-if="isEditing"
                type="text"
                @click="$emit('uploadFile','temporaryResidencePermit')"
              >
                <i class="el-icon-refresh" />
                更换
              </el-button>
            </td>
          </tr>

          <tr>
            <td class="label">奖惩记录</td>
            <td class="value">
              <RewardPunishment :user-i-d="userID" />
            </td>

            <td class="label">角色</td>
            <td class="value">
              <SetRoles
                v-model="profile.roles"
                :is-editing="isEditing"
              />
              <!--              <template v-if="atLeastN(profile.roles,1)">-->
              <!--                <el-tag-->
              <!--                  v-for="role in profile.roles"-->
              <!--                  :key="role.role_id"-->
              <!--                  type="info"-->
              <!--                >-->
              <!--                  {{ role.role.label_name }}-->
              <!--                </el-tag>-->
              <!--              </template>-->
              <!--              <span v-else>-</span>-->
            </td>
            <td class="label">介绍人</td>
            <td class="value">
              <ValueWithSelector
                v-model="profile.introducer"
                size="mini"
                filterable
                placeholder="请选择介绍人"
                style="width: 100%;"
                :is-editing="isEditing"
                :options="introduceList"
              />
            </td>
          </tr>
          <!--          <tr>-->
          <!--            <td class="label">介绍人所在部门</td>-->
          <!--            <td class="value">-->
          <!--              {{ value(profile,"introducerDepartment.user_company.department.name","-") }}-->
          <!--            </td>-->
          <!--          </tr>-->
        </tbody>
      </table>
    </div>

    <el-dialog
      title="更换宿舍"
      width="30%"
      :visible.sync="switchDormDialog.visible"
    >
      <Dorm @closeMain="handleSelectedDorm" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="switchDormDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="switchDormDialog.visible = false">确 定</el-button>
      </div>
    </el-dialog>
  </Block>
</template>

<style lang="scss">
.company-archives-container {
    .company-archives {
        width: 100%;
    }

    .row {
        margin-top: 6px;
        font-size: 14px;
        color: #333;
        .label {

        }
    }
}
</style>
